<template>
  <baidu-map
    ak="dtyxcfi1uY7StnaQFv56bOobsrn9gFNM"
    class="map"
    :center="center"
    :zoom="zoom"
    :scroll-wheel-zoom="true"
    :min-zoom="minZoom"
    @ready="readyHandler"
  >
    <info-marker
      v-for="device in devices"
      :key="device.id"
      :device="device"
    />
  </baidu-map>
</template>

<script>
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import InfoMarker from './InfoMarker'

export default {
  name: 'Map',

  data() {
    return {
      center: { lat: 0, lng: 0 },
      zoom: 3,
      minZoom: 2
    }
  },

  components: {
    BaiduMap,
    InfoMarker
  },

  props: {
    devices: {
      type: Array,
      required: true
    }
  },

  methods: {
    readyHandler({ BMap, map }) {
      if (this.devices.length > 1) {
        const pointCollection = this.devices.reduce((prev, cur) => {
          prev.push(cur.location)
          return prev
        }, [])

        const view = map.getViewport(eval(pointCollection))
        this.center = view.center
        this.zoom = view.zoom
        this.minZoom = this.zoom < 1 ? 0 : this.zoom - 1
      } else {
        this.center.lat = this.devices[0].location.lat
        this.center.lng = this.devices[0].location.lng
        this.zoom = 18
        this.minZoom = this.zoom - 1
      }
    }
  }
}
</script>

<style lang="scss">
.map {
  width: 100%;
  height: 100%;
}
</style>
